<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '产品列表',
  },
}
</route>
<template>
  <view class="service-listing-page min-h-screen bg-gray-50">
    <view class="px-2" v-if="subCategoryList.length > 0">
      <view class="bg-white rounded-lg shadow-lg p-2">
        <view class="service-types-container overflow-x-auto">
          <view class="flex space-x-4 pb-2">
            <view v-for="subCategory in subCategoryList" :key="subCategory.id"
              class="flex flex-col items-center flex-shrink-0 cursor-pointer"
              :class="cateId === subCategory.id ? 'text-orange-500' : 'text-gray-600'"
              @click="setCateId(subCategory.id)">
              <view class="w-14 h-14 rounded-full flex items-center justify-center mb-1"
                :class="cateId === subCategory.id ? 'bg-orange-100' : 'bg-gray-100'">
                <image :src="subCategory.image" :alt="subCategory.cateName" class="w-8 h-8" />
              </view>
              <text class="text-xs">{{ subCategory.cateName }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="px-2 pb-20" :class="{ 'mt-2': subCategoryList.length > 0 }">
      <view class="bg-white rounded-lg shadow-lg p-2 mb-4">
        <view class="flex justify-around">
          <view v-for="(option, index) in sortOptions" :key="index" class="px-5 py-1 text-sm rounded-full" :class="activeSortOption === index ? 'bg-orange-500 text-white' : 'bg-gray-100 text-gray-700'
            " @click="setActiveSortOption(option, index)">
            {{ option.label }}
          </view>
        </view>
      </view>

      <!-- 搜索框 -->
      <view
        class="flex-1 bg-white mb-4 rounded-lg overflow-hidden py-2 mt-4 flex flex-row justify-between items-center border border-solid border-red-7 mt-2">
        <input class="pl-2 text-xs" v-model="queryParams.name" placeholder="🔍   输入商品名称" :auto-focus="true" />
        <view class="w-18 text-4 h-7 text-red-7 leading-7 bl text-center font-bold" @click="handleSearch">
          搜索
        </view>
      </view>
      <!--  -->

      <view class="space-y-4">
        <wd-status-tip image="search" v-if="productList.length === 0" tip="当前搜索无结果" />

        <view v-for="service in productList" :key="service.id" class="bg-white rounded-lg shadow p-2"
          @click="openServiceModal(service)">
          <view class="flex">
            <image :src="service.image" :alt="service.name" class="w-24 h-24 rounded-lg object-cover mr-4" />
            <view class="flex-1 flex flex-col justify-between items-start">
              <view class="flex justify-between items-start">
                <view class="font-bold text-gray-800 mr-2">{{ service.name }}</view>
                <text class="text-xs px-2 py-1 bg-orange-100 text-orange-600 rounded">
                  {{ service.storeName }}
                </text>
              </view>

              <view class="flex items-center mt-1 text-xs text-gray-500">
                <text>销量 {{ service.sales }}</text>
              </view>

              <view class="w-full flex justify-between items-end mt-2">
                <view class="flex items-baseline">
                  <text class="text-xs text-orange-500 mr-0.5">¥</text>
                  <text class="text-lg font-bold text-orange-500">{{ service.vipPrice }}</text>
                  <text class="text-xs text-gray-500 ml-1">起</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- Loading Modal -->
    <view v-if="isLoading" class="fixed inset-0 bg-black/30 flex items-center justify-center z-30">
      <view class="bg-white rounded-lg p-6 flex flex-col items-center">
        <view class="w-12 h-12 border-4 border-orange-500 border-t-transparent rounded-full animate-spin mb-4"></view>
        <view class="text-gray-700">加载中...</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { http } from '@/utils/http'
import dayjs from 'dayjs'

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  type: '',
  sequence: 2,
  name: '',
})

const parentId = ref('')
const subCategoryList = ref([])
const cateId = ref(0)
const activeSortOption = ref(0)
const productList = ref([])
const isLoading = ref(false)
const hasMoreData = ref(true)

const getSubCategoryList = async () => {
  let res = await http.get('/api/home/categories', {
    pid: 0,
    type: 2,
  })
  if (res.code == 200) {
    subCategoryList.value = res.data.categories
    if (subCategoryList.value.length > 0) {
      cateId.value = subCategoryList.value[0].id
    } else {
      cateId.value = parentId.value
    }
    queryParams.pageNum = 1
    getProductList()
  }
}

const getProductList = async () => {
  let res = await http.get('/api/home/products', {
    ...queryParams.value,
    name: queryParams.value.name.trim(),
    cateId: cateId.value,
    type: 2,
  })
  if (res.code == 200) {
    console.log('res', res)
    if (queryParams.value.pageNum == 1) {
      productList.value = res.data.products
    } else {
      productList.value = productList.value.concat(res.data.products)
    }
  }
}

const setCateId = (id) => {
  if (cateId.value != id) {
    cateId.value = id

    queryParams.value.type = ''
    queryParams.value.sequence = 'desc'
    queryParams.value.pageNum = 1

    getProductList()
  }
}

// Sort Options
const sortOptions = [
  {
    label: '默认排序',
    type1: '',
    sequence: 'desc',
  },
  {
    label: '销量优先',
    type1: '1',
    sequence: 'desc',
  },
  {
    label: '价格优先',
    type1: '2',
    sequence: 'desc',
  },
  // { label: '距离优先', type1: '', sequence: 'desc' },
]

const total = ref(0)

const setActiveSortOption = (option, index) => {
  if (activeSortOption.value == index) {
    return
  }

  activeSortOption.value = index
  queryParams.value.type1 = option.type1
  queryParams.value.sequence = option.sequence
  queryParams.value.pageNum = 1
  getProductList()
}

const handleSearch = () => {
  queryParams.value.pageNum = 1
  getProductList()
}

const loadMore = async () => {
  isLoading.value = true
  try {
    queryParams.value.pageNum = queryParams.value.pageNum + 1
    await getProductList()
  } catch (error) {
    console.log('error', error)
  } finally {
    isLoading.value = false
  }
}

onReachBottom(() => {
  if (total.value > productList.value.length) {
    loadMore()
  } else {
    uni.showToast({
      title: '没有更多了',
      icon: 'none',
      mask: false,
    })
  }
})

// Service Detail Modal
const showServiceModal = ref(false)
const selectedService = ref({})
const isSubmitting = ref(false)

const orderForm = ref({
  content: '',
  images: '',
  name: '',
  phone: '',
  detailedAddress: '',
  upperTime: '',
})

const openServiceModal = (service) => {
  uni.navigateTo({ url: '/pages/product/detail?scene=' + service.id })

  return
  // 旧的方式
  // console.log('%c [ service ]-355', 'font-size:13px; background:pink; color:#bf2c9f;', service)
  // selectedService.value = service
  // showServiceModal.value = true

  // orderForm.value = {
  //   id: service.id,
  //   content: '',
  //   images: '',
  //   name: '',
  //   phone: '',
  //   detailedAddress: '',
  //   upperTime: dayjs().add(3, 'hour').startOf('hour').format('YYYY-MM-DD HH:mm:ss'),
  // }
}

const submitOrder = async () => {
  isSubmitting.value = true
  // 提交
  try {
    let data = {
      number: 1,
      remark: '',
      orderType: 3,
      groupId: 0,
      couponId: 0,
      ...orderForm.value,
    }

    console.log('data', data)

    let res = await http({
      url: '/api/wxPayApplet/productWxPay',
      method: 'POST',
      data: data,
    })

    if (res.code == 200) {
      uni.requestPayment({
        provider: 'wxpay',
        timeStamp: res.data.timeStamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: 'MD5',
        paySign: res.data.paySign,
        success: (res) => {
          uni.showToast({
            title: '支付成功',
            icon: 'success',
          })
        },
        fail: (err) => {
          uni.showToast({
            title: '支付失败',
            icon: 'none',
          })
        },
      })
    }
  } catch (error) {
    console.log('error', error)
  } finally {
    showServiceModal.value = false
    isSubmitting.value = false
  }
}

onLoad((option) => {
  parentId.value = option.cateId
  if (option && option.query) {
    queryParams.value.name = option.query
  }

  getSubCategoryList()
})
</script>

<style scoped>
.service-types-container {
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE and Edge */
}

.service-types-container::-webkit-scrollbar {
  display: none;
  /* Chrome, Safari, Opera */
}

.bl {
  border-left: 3rpx solid rgb(185 28 28);
}
</style>
